package com.ruoyi.business.controller;

import com.ruoyi.business.service.s7.S7ConnectionManagerService;
import com.ruoyi.business.service.IEquipmentVariablesHistoryService;
import com.ruoyi.business.domain.EquipmentVariablesHistory;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * S7连接测试控制器
 * 用于测试并行读取功能
 *
 * @author qiancheng
 * @date 2025-09-02
 */
@RestController
@RequestMapping("/business/s7test")
public class S7TestController extends BaseController {

    @Autowired
    private S7ConnectionManagerService s7ConnectionManagerService;

    @Autowired
    private IEquipmentVariablesHistoryService equipmentVariablesHistoryService;

    /**
     * 获取S7连接状态
     */
    @GetMapping("/status")
    public AjaxResult getConnectionStatus() {
        try {
            Map<String, Object> stats = s7ConnectionManagerService.getReadingPerformanceStats();
            return AjaxResult.success("获取连接状态成功", stats);
        } catch (Exception e) {
            return AjaxResult.error("获取连接状态失败: " + e.getMessage());
        }
    }

    /**
     * 手动触发变量读取测试
     */
    @PostMapping("/manual-read")
    public AjaxResult triggerManualRead() {
        try {
            CompletableFuture<Map<String, Object>> future = s7ConnectionManagerService.triggerManualRead();
            Map<String, Object> results = future.get(); // 同步等待结果
            return AjaxResult.success("手动读取完成", results);
        } catch (Exception e) {
            return AjaxResult.error("手动读取失败: " + e.getMessage());
        }
    }

    /**
     * 异步触发变量读取测试
     */
    @PostMapping("/async-read")
    public AjaxResult triggerAsyncRead() {
        try {
            s7ConnectionManagerService.triggerManualRead()
                .thenAccept(results -> {
                    logger.info("异步读取完成，结果: {}", results);
                })
                .exceptionally(throwable -> {
                    logger.error("异步读取失败", throwable);
                    return null;
                });
            return AjaxResult.success("异步读取任务已启动");
        } catch (Exception e) {
            return AjaxResult.error("启动异步读取失败: " + e.getMessage());
        }
    }

    /**
     * 触发定时读取任务
     */
    @PostMapping("/trigger-scheduled")
    public AjaxResult triggerScheduledRead() {
        try {
            s7ConnectionManagerService.readAllActiveVariables();
            return AjaxResult.success("定时读取任务已触发");
        } catch (Exception e) {
            return AjaxResult.error("触发定时读取失败: " + e.getMessage());
        }
    }

    /**
     * 查询最近的历史数据记录
     */
    @GetMapping("/recent-history")
    public AjaxResult getRecentHistory(@RequestParam(defaultValue = "S7_READ") String operationType) {
        try {
            List<EquipmentVariablesHistory> historyList = equipmentVariablesHistoryService
                    .selectEquipmentVariablesHistoryByOperationType(operationType);
            
            // 只返回最近的10条记录
            List<EquipmentVariablesHistory> recentHistory = historyList.stream()
                    .limit(10)
                    .collect(java.util.stream.Collectors.toList());
            
            return AjaxResult.success("获取历史数据成功", recentHistory);
        } catch (Exception e) {
            return AjaxResult.error("获取历史数据失败: " + e.getMessage());
        }
    }

    /**
     * 根据变量名称查询历史数据
     */
    @GetMapping("/history-by-variable")
    public AjaxResult getHistoryByVariable(@RequestParam String variableName) {
        try {
            List<EquipmentVariablesHistory> historyList = equipmentVariablesHistoryService
                    .selectEquipmentVariablesHistoryByVariableName(variableName);
            
            return AjaxResult.success("获取变量历史数据成功", historyList);
        } catch (Exception e) {
            return AjaxResult.error("获取变量历史数据失败: " + e.getMessage());
        }
    }
}